#!/usr/bin/env python3
import sys
import argparse
import signal
import subprocess
from idea_proxy import IDEAProxy
from simple_dashboard_fixed import SimpleDashboard
from cert_generator import CertificateGenerator
from proxy_config import ProxyConfig

def signal_handler(sig, frame):
    print('\nShutting down proxy...')
    sys.exit(0)

def main():
    parser = argparse.ArgumentParser(description='IDEA Network Proxy Monitor')
    parser.add_argument('--proxy-port', type=int, 
                       help='Proxy server port (default: from config or 8080)')
    parser.add_argument('--dashboard-port', type=int,
                       help='Dashboard port (default: from config or 8081)')
    parser.add_argument('--no-dashboard', action='store_true',
                       help='Disable web dashboard')
    parser.add_argument('--generate-certs', action='store_true',
                       help='Generate SSL certificates for HTTPS interception')
    parser.add_argument('--config', type=str, default='proxy_config.json',
                       help='Configuration file path (default: proxy_config.json)')
    
    # Upstream proxy configuration
    parser.add_argument('--upstream-host', type=str, 
                       help='Upstream proxy host')
    parser.add_argument('--upstream-port', type=int, 
                       help='Upstream proxy port')
    parser.add_argument('--upstream-username', type=str,
                       help='Upstream proxy username')
    parser.add_argument('--upstream-password', type=str,
                       help='Upstream proxy password')
    
    args = parser.parse_args()
    
    # Load configuration
    config = ProxyConfig(args.config)
    
    # Handle certificate generation
    if args.generate_certs:
        print("Generating SSL certificates...")
        cert_gen = CertificateGenerator()
        if cert_gen.create_ca_certificate():
            print("Certificates generated successfully!")
            print(cert_gen.get_install_instructions())
        else:
            print("Failed to generate certificates")
        return
    
    # Set up signal handlers
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # Get configuration values (command line args override config file)
    proxy_config = config.get_proxy_config()
    proxy_port = args.proxy_port or proxy_config['port']
    
    dashboard_config = config.get_dashboard_config()
    dashboard_port = args.dashboard_port or dashboard_config['port']
    
    # Configure upstream proxy (command line args override config file)
    upstream_proxy = None
    if args.upstream_host and args.upstream_port:
        # Use command line arguments
        upstream_proxy = {
            'host': args.upstream_host,
            'port': args.upstream_port,
            'username': args.upstream_username,
            'password': args.upstream_password
        }
        print(f"Upstream proxy (CLI): {args.upstream_host}:{args.upstream_port}")
        if args.upstream_username:
            print(f"Using authentication: {args.upstream_username}")
    else:
        # Use config file
        upstream_proxy = config.get_upstream_proxy_config()
        if upstream_proxy:
            print(f"Upstream proxy (config): {upstream_proxy['host']}:{upstream_proxy['port']}")
            if upstream_proxy.get('username'):
                print(f"Using authentication: {upstream_proxy['username']}")
    
    # Create and start proxy
    proxy = IDEAProxy('0.0.0.0', proxy_port, upstream_proxy)
    
    # Start dashboard if enabled
    dashboard = None
    if not args.no_dashboard and dashboard_config.get('enabled', True):
        dashboard = SimpleDashboard(proxy, dashboard_port)
        dashboard.start()
    
    # 获取WSL IP地址
    try:
        result = subprocess.run(['hostname', '-I'], capture_output=True, text=True, timeout=5)
        wsl_ip = result.stdout.strip().split()[0] if result.stdout.strip() else "WSL_IP"
    except:
        wsl_ip = "WSL_IP"
    
    print(f"IDEA Proxy Monitor")
    print(f"=================")
    print(f"🌐 代理服务器:")
    print(f"   WSL内访问: http://127.0.0.1:{proxy_port}")
    print(f"   Windows访问: http://{wsl_ip}:{proxy_port}")
    if dashboard:
        print(f"🖥️  监控面板:")
        print(f"   WSL内访问: http://localhost:{dashboard_port}")
        print(f"   Windows访问: http://{wsl_ip}:{dashboard_port}")
    if upstream_proxy:
        print(f"🔗 上游代理: {upstream_proxy['host']}:{upstream_proxy['port']}")
    print(f"")
    print(f"📋 配置步骤:")
    print(f"1. 在IDEA中配置HTTP代理为: {wsl_ip}:{proxy_port}")
    print(f"2. 重启IntelliJ IDEA")
    print(f"3. 在监控面板或日志中查看请求")
    print(f"")
    print(f"Configuration commands:")
    print(f"  python3 proxy_config.py set-upstream HOST PORT [USER] [PASS]")
    print(f"  python3 proxy_config.py show")
    print(f"")
    print(f"Press Ctrl+C to stop...")
    
    try:
        proxy.start()
    except KeyboardInterrupt:
        print("\nShutting down...")
        if dashboard:
            dashboard.stop()
        proxy.stop()
        proxy.save_logs_to_file()

if __name__ == '__main__':
    main()